package com.platform.modules.acme.component;

import com.platform.common.utils.DateUtils;
import com.platform.common.utils.JedisUtil;
import com.platform.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.ConnectException;
import java.text.NumberFormat;
import java.time.Clock;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Formatter;
import java.util.UUID;

@Component
public class AcmeCache {

    static Logger logger = LoggerFactory.getLogger(AcmeCache.class);

    @Autowired
    JedisUtil jedisUtil;

    /**
     * get orderCode
     *
     * @return
     */
    public String getOrderCode() {
        String now = DateTimeFormatter.ofPattern("yyyyMMdd").format(LocalDate.now());
        int orderCode = jedisUtil.getIncrNumber("orderCode");
        if (orderCode == 0) {
            orderCode = 1;
            jedisUtil.set("orderCode", String.valueOf(orderCode),0);
        } else if (orderCode == -1) {
            logger.error("获取顺序订单号出错");
            //出错则给UUID
            return UUID.randomUUID().toString();
        }
        NumberFormat format = NumberFormat.getNumberInstance();
        format.setMinimumIntegerDigits(8);
        //去除数字逗号
        format.setGroupingUsed(false);
        return now + format.format(orderCode);
    }


    /**
     * <pre>
     * 判断是否限制,true则不能继续申请
     * </pre>
     *
     * @return true/false
     */
    public boolean getLimit(String email) throws ConnectException {
        String dayLimit = email + "_" + DateTimeFormatter.ofPattern("yyyyMMdd").format(LocalDate.now());
        int dayLimitSec = 24 * 60 * 60;
        int countLimitSec = 2 * 60;
//        String limit_value = jedisUtil.get(dayLimit);

        String limitCount = "9";
        if(!jedisUtil.getResource().isConnected())
            throw new ConnectException("can't connect to jedis!");
        if (!jedisUtil.exists(dayLimit)) {
            //初始化次数，
            jedisUtil.set(dayLimit, limitCount, dayLimitSec);
            jedisUtil.set(email, email, countLimitSec);
            return false;
        } else {
            if (jedisUtil.get(email) == null) {
                //自减
                int result = jedisUtil.getDecr(dayLimit);
                if (result == 0) {
                    //一天的申请次数上限
                    return true;
                }
                jedisUtil.set(email, email, countLimitSec);
                return false;
            } else {
                //次数间隔时间未到
                return true;
            }
        }
    }

}
